package com.bifrost.listener;

import com.bifrost.common.constant.SessionConstant;
import com.bifrost.service.RegAndLogService;
import com.bifrost.util.HttpContextUtils;
import com.bifrost.wechat.event.OauthCompleteEvent;
import com.bifrost.wechat.service.WxServiceContext;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@Component
public class OauthCompleteListener implements ApplicationListener<OauthCompleteEvent> {
    private static final Logger logger = LoggerFactory.getLogger(OauthCompleteListener.class);
    @Autowired
    WxServiceContext wxServiceContext;
    @Autowired
    RegAndLogService loginService;
    @Override
    public void onApplicationEvent(OauthCompleteEvent oauthCompleteEvent) {
        WxMpUser user = (WxMpUser) oauthCompleteEvent.getSource();
        logger.info("获取的userInfo:" + user.toString());
            try {
                HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
                HttpServletResponse response = HttpContextUtils.getHttpServletResponse();
                if(request!=null&&response!=null){
                    HttpSession  session = request.getSession();
                    session.setAttribute(SessionConstant.OPEN_ID, user.getOpenId());
                    session.setAttribute(SessionConstant.NICKNAME, user.getNickname());
                    session.setAttribute(SessionConstant.SEX, user.getSex());
                    session.setAttribute(SessionConstant.HEAD_IMG_URL, user.getHeadImgUrl());
                    session.setAttribute(SessionConstant.CITY, user.getCity());
                    session.setAttribute(SessionConstant.PROVINCE, user.getProvince());
                    session.setAttribute(SessionConstant.APP_ID,oauthCompleteEvent.getAppId());
                    //添加门店信息到session中
                    session.setAttribute(SessionConstant.STORE_ID,wxServiceContext.getStoreId(oauthCompleteEvent.getAppId()));
                    //自动登录
                loginService.loginAuto(request,response);
                }
            } catch (Exception e) {
               logger.error(e.getMessage(),e);
            }
        }
}
